package com.xiaoxing.gongqiju.mvp.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.hss01248.frescopicker.FrescoIniter;
import com.hss01248.photoouter.PhotoCallback;
import com.hss01248.photoouter.PhotoUtil;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.xiaoxing.gongqiju.R;
import com.xiaoxing.gongqiju.R2;
import com.xiaoxing.gongqiju.di.component.DaggerLiaoCheng_GongQiJu_PaiZhaoZhuiZongComponent;
import com.xiaoxing.gongqiju.di.module.LiaoCheng_GongQiJu_PaiZhaoZhuiZongModule;
import com.xiaoxing.gongqiju.mvp.contract.LiaoCheng_GongQiJu_PaiZhaoZhuiZongContract;
import com.xiaoxing.gongqiju.mvp.presenter.LiaoCheng_GongQiJu_PaiZhaoZhuiZongPresenter;
import com.xiaoxing.gongqiju.mvp.ui.entity.LiaoCheng_GongQiJu_PaiZhaoZhuiZong;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.iwf.photopicker.utils.ProxyTools;
import me.jessyan.armscomponent.commonres.utils.BottomDialogUtil;
import com.jess.arms.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import okhttp3.RequestBody;

import static com.jess.arms.base.BaseConstants.SCAN_REQUEST_CODE;
import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.GONGQIJU_LIAOCHENG_ACTIVITY_LIAO_CHENG_GONG_QI_JU_PAI_ZHAO_ZHUI_ZONG)
public class LiaoCheng_GongQiJu_PaiZhaoZhuiZongActivity extends BaseActivity<LiaoCheng_GongQiJu_PaiZhaoZhuiZongPresenter> implements LiaoCheng_GongQiJu_PaiZhaoZhuiZongContract.View {


    public LocationClient mLocationClient = null;
    @BindView(R2.id.img_er_wei_ma)
    ImageView imgErWeiMa;
    @BindView(R2.id.img_zhao_pian)
    ImageView imgZhaoPian;
    @BindView(R2.id.tv_dang_qian_di_zhi)
    TextView tvDangQianDiZhi;
    @BindView(R2.id.tv_yi_sao_miao_er_wei_ma)
    TextView tvYiSaoMiaoErWeiMa;
    @BindView(R2.id.btn_bao_cun)
    Button btnBaoCun;
    private String scanResult = "";
    private double mLatitude = 0;
    private double mLongitude = 0;
    private MyLocationListener myListener = new MyLocationListener();
    private String mImgPic = "";
    private BottomDialogUtil mBottomDialogUtilShare;

    private void paiZhao() {
        LinearLayout root = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.sales_client_bottom_dialog_pai_zhao, null);
        Button btn_xiang_ce = root.findViewById(me.iwf.photopicker.R.id.btn_xiang_ce);
        Button ben_xiang_ji = root.findViewById(me.iwf.photopicker.R.id.ben_xiang_ji);
        Button btn_qu_xiao = root.findViewById(me.iwf.photopicker.R.id.btn_qu_xiao);
        btn_qu_xiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
            }
        });
        btn_xiang_ce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();

                PhotoUtil.begin()
                        .setNeedCropWhenOne(false)
                        .setNeedCompress(false)
                        .setMaxSelectCount(1)

                        .start(LiaoCheng_GongQiJu_PaiZhaoZhuiZongActivity.this, 33, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
//
                                try {
                                    mImgPic = ArmsUtils.bitmapToString(compressedPath);
                                    Bitmap bitmap = BitmapFactory.decodeFile(compressedPath);
                                    imgZhaoPian.setImageBitmap(bitmap);
                                } catch (Exception e) {
                                    e.printStackTrace();

                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
//                                refresh1(originalPaths);

                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });
        ben_xiang_ji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
                PhotoUtil.statusBarColor = R.color.public_black;
                PhotoUtil.titleBarColor = R.color.public_black;
                PhotoUtil.cropAvatar(true).setCropMuskOvalFalse()
                        .start(LiaoCheng_GongQiJu_PaiZhaoZhuiZongActivity.this, 23, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
                                try {
                                    mImgPic = ArmsUtils.bitmapToString(compressedPath);
                                    Bitmap bitmap = BitmapFactory.decodeFile(compressedPath);
                                    imgZhaoPian.setImageBitmap(bitmap);
                                } catch (Exception e) {
                                    e.printStackTrace();

                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });

        mBottomDialogUtilShare = new BottomDialogUtil(LiaoCheng_GongQiJu_PaiZhaoZhuiZongActivity.this, root);
        mBottomDialogUtilShare.showDiaolog();

    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLiaoCheng_GongQiJu_PaiZhaoZhuiZongComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .liaoCheng_GongQiJu_PaiZhaoZhuiZongModule(new LiaoCheng_GongQiJu_PaiZhaoZhuiZongModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_liao_cheng__gong_qi_ju__pai_zhao_zhui_zong; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    private void toScanQRCodeActivity() {
        Intent openCameraIntent = new Intent(this, LiaoCheng_GongQiJu_ScanActivity.class);
        mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, 101);
        startActivityForResult(openCameraIntent, 101);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 101) {
            Bundle bundle = data.getExtras();
            scanResult = bundle.getString("scan_result");
            tvYiSaoMiaoErWeiMa.setText("已扫描的二维码：" + scanResult);
        } else {
            if (resultCode != 0)
                PhotoUtil.onActivityResult(this, requestCode, resultCode, data);
        }

    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_liao_cheng__gong_qi_ju__pai_zhao_zhui_zong));
        //getLiaoCheng_GongQiJu_PaiZhaoZhuiZongData();
        PhotoUtil.init(this, new FrescoIniter());

        initBaiDuLocation();
    }

    @Override
    public void getLiaoCheng_GongQiJu_PaiZhaoZhuiZongDataSuccess(LiaoCheng_GongQiJu_PaiZhaoZhuiZong entityData) {

        showMessage(entityData.getMessage());
        if (entityData.getCode().equals("200")) {
            killMyself();
        }
    }

    private void getLiaoCheng_GongQiJu_PaiZhaoZhuiZongData() {

        String jsonData = "{\n" +
                "  \"tid\": " + "" + ",\n" +
                "  \"mid\": " + scanResult + ",\n" +
                "  \"trackuserid\": " + mSharedPreferencesHelper.getString(BaseConstants.UID) + ",\n" +
                "  \"lat\": \"" + mLatitude + "\",\n" +
                "  \"lng\": \"" + mLongitude + "\",\n" +
                "  \"tracktime\": \"" + ArmsUtils.getDataTime("yyyy-MM-dd HH:mm:ss") + "\",\n" +
                "  \"picId\": 0,\n" +
                "  \"Pictures\": [\n" +
                "    {\n" +
                "      \"PictureId\": 0,\n" +
                "      \"PictureExtension\": \"jpg\",\n" +
                "      \"Picture\": \"" + mImgPic + "\"\n" +
                "    }\n" +

                "  ]\n" +
                "}";
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonData);

        mPresenter.getLiaoCheng_GongQiJu_PaiZhaoZhuiZongData(body);
    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog(this);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    private void initBaiDuLocation() {
        //BDAbstractLocationListener为7.2版本新增的Abstract类型的监听接口
        //原有BDLocationListener接口暂时同步保留。具体介绍请参考后文第四步的说明
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);

        //可选，是否需要地址信息，默认为不需要，即参数为false
        //如果开发者需要获得当前点的地址信息，此处必须为true
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；

        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认GCJ02
        //GCJ02：国测局坐标；
        //BD09ll：百度经纬度坐标；
        //BD09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回WGS84类型坐标

        option.setScanSpan(60000);
//        option.setScanSpan(60000);
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true


        option.setLocationNotify(true);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //可选，V7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前Wi-Fi是否超出有效期，若超出有效期，会先重新扫描Wi-Fi，然后定位

        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明


        mLocationClient.start();
        //mLocationClient为第二步初始化过的LocationClient对象
        //调用LocationClient的start()方法，便可发起定位请求
    }

    @Override
    public void killMyself() {
        finish();
    }


    @OnClick({R2.id.img_er_wei_ma, R2.id.img_zhao_pian, R2.id.btn_bao_cun})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.img_er_wei_ma) {
            toScanQRCodeActivity();
        } else if (id == R.id.img_zhao_pian) {
            paiZhao();
        } else if (id == R.id.btn_bao_cun) {
            if (scanResult.equals("")) {
                showMessage("请先扫描工具二维码");
                toScanQRCodeActivity();
                return;
            }
            if (mImgPic.equals("")) {
                showMessage("请先拍照");
                paiZhao();
                return;
            }

            getLiaoCheng_GongQiJu_PaiZhaoZhuiZongData();
        }
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
                double latitude = location.getLatitude();    //获取纬度信息
                double longitude = location.getLongitude();    //获取经度信息
                float radius = location.getRadius();    //获取定位精度，默认值为0.0f
                mLatitude = latitude;
                mLongitude = longitude;
                String coorType = location.getCoorType();
                //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
                int errorCode = location.getLocType();
                //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明

                LogUtils.debugEInfo("onReceiveLocation==" + location.getAddrStr() + "   经纬度==" + "lat=" + latitude + " lon" + longitude);
                tvDangQianDiZhi.setText(location.getAddrStr() + "   经纬度==" + "lat=" + latitude + " lon" + longitude);
            }//此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            else if (location.getLocType() == BDLocation.TypeOffLineLocation) {
                // 离线定位成功
                double lat = location.getLatitude();
                double lon = location.getLongitude();
                mLatitude = lat;
                mLongitude = lon;
                LogUtils.debugEInfo("baidu_location_result", "offline location success");
                LogUtils.debugEInfo("经纬度==lat=" + lat + " lon" + lon);
                tvDangQianDiZhi.setText(location.getAddrStr() + "   经纬度==" + "lat=" + lat + " lon" + lon);

            } else if (location.getLocType() == BDLocation.TypeGpsLocation) {
                // GPS定位成功
                double lat = location.getLatitude();
                double lon = location.getLongitude();
                mLatitude = lat;
                mLongitude = lon;
                LogUtils.debugEInfo("baidu_location_result", "Gps location success");
                LogUtils.debugEInfo("经纬度==lat=" + lat + " lon" + lon);
                tvDangQianDiZhi.setText(location.getAddrStr() + "   经纬度==" + "lat=" + lat + " lon" + lon);

            } else if (location.getLocType() == BDLocation.TypeOffLineLocationFail) {
                // 离线定位失败
                showMessage("GPS信号弱,定位失败,请到空旷的位置重新定位。");
                LogUtils.debugEInfo("baidu_location_result", "offline location fail");
                LogUtils.debugEInfo("GPS信号弱,定位失败,请到空旷的位置重新定位。");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocationNetworkFail) {
                // 离线定位失败
                showMessage("网络信号弱,定位失败,请检查网络状态。");
                LogUtils.debugEInfo("baidu_location_result", "Network location fail");
                LogUtils.debugEInfo("网络信号弱,定位失败,请检查网络状态。");
            } else {
//                showMessage("location type = " + location.getLocType());
                LogUtils.debugEInfo("baidu_location_result", "location type = " + location.getLocType());
                LogUtils.debugEInfo("location type = " + location.getLocType());
            }

        }
    }
}
